package com.effvi.taoke.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.effvi.taoke.constants.SessionKey;
/**
 * 后台系统控制器
 * @author kelvin.zhang
 *
 */
@Controller
@RequestMapping("/console")
public class ConsoleController {
	
	private static Logger logger = Logger.getLogger(ConsoleController.class);
	private final static String LOGIN_PAGE_PATH = "/admin/login";//后台登陆页
	private final static String COSONLE_PAGE_PATH = "/admin/index";//后台主页
	private final static String COSONLE_PATH = "/console";//后台主页
	@RequestMapping({"/",""})
	public String showIndexPage(HttpServletRequest request,@RequestHeader("Host") String hostname){
//		HttpSession session = request.getSession();
		logger.debug("来自"+request.getRemoteHost()+"正在访问后台管理系统");
//		ModelAndView model = new ModelAndView(LOGIN_PAGE_PATH);
//		model.addObject("redirect", redirect);
		return COSONLE_PAGE_PATH;
	}
	
	@RequestMapping(value={"/login","/login/"},method=RequestMethod.GET)
	public ModelAndView showLogin(HttpServletRequest request,@RequestParam(required=false) String redirect){
		HttpSession session = request.getSession();
		logger.debug("显示后台管理系统登录页");
		if(session.getAttribute(SessionKey.ADMIN_LOGIN_NAME) != null){
			logger.debug("正在访问后台管理系统"+session.getAttribute(SessionKey.ADMIN_LOGIN_NAME));
			return new ModelAndView(new RedirectView(COSONLE_PATH));
		}
		ModelAndView model = new ModelAndView(LOGIN_PAGE_PATH);
		model.addObject("redirect", redirect);
		return model;
	}
	
	@RequestMapping(value={"/login","/login/"},method=RequestMethod.POST)
	public String loginConsole(HttpServletRequest request,@RequestParam(value="username") String userName,@RequestParam(value="redirect",required=false) String redirect){
		HttpSession session = request.getSession();
		if(session.getAttribute(SessionKey.ADMIN_LOGIN_NAME) == null){
			session.setAttribute(SessionKey.ADMIN_LOGIN_NAME, userName);
			logger.debug("登录成功");
		}else{
			logger.debug("登录成功");
		}
		if(redirect != null){
			return "redirect:"+redirect;
		}else{
			return "redirect:"+LOGIN_PAGE_PATH;
		}
	}
	
	@RequestMapping({"/logout","/logout/"})
	public String logoutConsole(HttpServletRequest request){
		HttpSession session = request.getSession();
		if(session.getAttribute(SessionKey.ADMIN_LOGIN_NAME) != null){
			session.removeAttribute(SessionKey.ADMIN_LOGIN_NAME);
		}
		return LOGIN_PAGE_PATH;
	}
}
